package com.killer.catalina;

import com.killer.util.HttpProtocolUtil;
import com.killer.view.Request;
import com.killer.view.Response;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.util.List;

/**
 * Engine的实现类
 */
public class StandardEngine implements Engine{

    /**
     * 一个Engine下面可以配置多个host
     */
    private List<Host> hosts;

    public List<Host> getHosts() {
        return hosts;
    }

    public void setHosts(List<Host> hosts) {
        this.hosts = hosts;
    }

    @Override
    public void start() {
        //启动下面所有的host
        if (CollectionUtils.isNotEmpty(hosts)) {
            for (Host host : hosts) {
                host.start();
            }
        }
    }

    public StandardHost mapperHost(Request request, Response response) throws IOException {
        if (CollectionUtils.isEmpty(hosts)) {
            response.response(HttpProtocolUtil.getRep404Header());
        }
        for (Host host : hosts) {
            StandardHost standardHost=(StandardHost)host;
            if (StringUtils.equals(request.getHost(), standardHost.getName())) {
                return standardHost;
            }
        }
        return null;
    }
}
